package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserserviceImpl implements UserService {

    public static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private UserMapper userMapper;

    private final WeChatProperties weChatProperties;

    public UserserviceImpl(WeChatProperties weChatProperties) {
        this.weChatProperties = weChatProperties;
    }

    /**
     * 微信登录
     *
     * @param userLoginDTO 用户登录的DTO对象
     * @return 登录成功的用户对象
     */
    @Override
    public User wxlogin(UserLoginDTO userLoginDTO) {
        // 创建一个Map对象用于存储请求参数
        Map<String,String> map=new HashMap<>();
        // 设置appid
        map.put("appid",weChatProperties.getAppid());
        // 设置secret
         map.put("secret",weChatProperties.getSecret());

        // 设置授权类型
        map.put("grant_type","authorization_code");
        // 设置js_code
        map.put("js_code",userLoginDTO.getCode());
        System.out.println(weChatProperties);
        // 发送GET请求，获取微信服务器返回的JSON字符串
        String json= HttpClientUtil.doGet(WX_LOGIN,map);

        // 将JSON字符串解析为JSONObject对象
        JSONObject jsonObject = JSON.parseObject(json);

        // 从JSONObject对象中获取openid
        String openid = jsonObject.getString("openid");
        // 根据openid查询用户信息
        User user=userMapper.getByOpenid(openid);
        if (openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 如果openid为空，则创建一个新用户并插入到数据库中
        if (user==null){
            user=User.builder()
                    // 设置openid
                    .openid(openid)
                    // 设置创建时间
                    .createTime(LocalDateTime.now())
                    // 构建User对象
                    .build();
            // 插入新用户到数据库中
            userMapper.insert(user);
        }



        System.out.println("----------------------------------");
        System.out.println(user);
        // 返回用户对象
        return user;
    }

}
